<template>
  <el-dialog :visible.sync="dialogVisible" append-to-body width="600px" :title="prodAttrTitle" @close="handleAttributeClose">
    <el-form ref="productAttrForm" v-loading="categoryAttrLoading" label-position="right" :model="productAttr" label-width="80px">
      <el-row>
        <el-col v-for="(item, index) in productAttr.categoryAttributeList" :key="index" :span="24">
          <el-form-item
            :label="item.name"
            :prop="'categoryAttributeList.'+index+'.value'"
            :rules="[{ required: true, message: item.optionType!=='2'?'请选择' + item.name:'请输入' + item.name, trigger: 'change' }]"
          >
            <el-radio-group v-if="item.optionType==='0'" v-model="item.value">
              <div v-for="(optional,idx) in item.optional" :key="idx" style="display: inline-block;padding-right: 10px">
                <el-radio :label="optional" style="margin-right: 10px" />
                <el-button
                  v-if="item.manuallyAdded&&item.manuallyAdded==='1'"
                  type="text"
                  style="font-size: 12px"
                  @click="deleteCategoryAttr(item,index,optional)"
                >删除</el-button>
              </div>
            </el-radio-group>
            <el-checkbox-group v-else-if="item.optionType==='1'" v-model="item.value">
              <div v-for="(optional,idx) in item.optional" :key="idx" style="display: inline-block;padding-right: 10px">
                <el-checkbox :label="optional" style="margin-right: 10px" />
                <el-button
                  v-if="item.manuallyAdded&&item.manuallyAdded==='1'"
                  type="text"
                  style="font-size: 12px"
                  @click="deleteCategoryAttr(item,index,optional)"
                >删除</el-button>
              </div>
            </el-checkbox-group>
            <div v-else>
              <el-input v-model="item.value" name="prod_length" auto-complete="on" style="margin-right: 10px" placeholder="请填写长度,如315-320" />
            </div>
            <div
              v-show="!productAttr.newAttr[index].show&&item.optionType!=='2'"
              style="font-size: 14px"
            >没有想要的{{ item.name }}？<el-button type="text" @click="showInput(productAttr.newAttr[index])">点击手动添加</el-button></div>
            <div v-if="item.manuallyAdded&&item.manuallyAdded==='1'&&productAttr.newAttr[index].show">
              <el-input v-model="productAttr.newAttr[index].value" :placeholder="'请输入想要添加的'+item.name" style="width: 200px;margin-right: 10px" />
              <el-button type="text" @click="saveCategoryAttr(item,index,productAttr.newAttr[index])">添加</el-button>
              <el-button type="text" @click="disableInput(productAttr.newAttr[index])">取消</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity" :rules="{ required: true, message: '请输入数量', trigger: 'change'}">
            <el-input v-model="productAttr.quantity" name="prod_quantity" auto-complete="on" type="number" placeholder="请输入数量" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单价" prop="unitPrice" :rules="{ required: true, message: '请输入单价', trigger: 'change'}">
            <el-input v-model="productAttr.unitPrice" name="prod_unit_price" auto-complete="on" type="number" placeholder="请输入单价" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :loading="categoryAttrLoading" type="text" @click="handleAttributeClose">取消</el-button>
      <el-button :loading="categoryAttrLoading" type="primary" @click="handleAttributeChange">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { selectByCategoryId, updateCategoryAttributeById } from '@/api/erp/categoryAttribute'

export default {
  name: 'ProductAttributeModule',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      moldData: {},
      productAttr: {
        unitPrice: '',
        quantity: '',
        newAttr: [],
        categoryAttributeList: []
      },
      categoryAttrLoading: false,
      prodAttrTitle: '',
      dialogVisible: this.visible
    }
  },
  methods: {
    init(row) {
      this.moldData = row
      this.prodAttrTitle = '请选择【' + row.moldName + '】的产品属性'
      this.categoryAttrLoading = true
      selectByCategoryId(row.categoryId).then(resp => {
        if (resp.success) {
          const array = []
          for (let i = 0; i < resp.data.length; i++) {
            array[i] = {}
            array[i].value = ''
            array[i].show = false
            var dataListElement = resp.data[i]
            if (dataListElement.optionType !== '2') {
              dataListElement.optional = dataListElement.optional.split('|')
            }
            if (dataListElement.optionType !== '2') {
              // 初始化el-checkbox数据 ！！！！！
              dataListElement.value = []
            } else {
              dataListElement.value = ''
            }
          }
          this.productAttr.categoryAttributeList = resp.data
          this.productAttr.newAttr = array
        }
      }).finally(() => {
        this.categoryAttrLoading = false
        this.$refs.productAttrForm.resetFields()
        this.productAttr.unitPrice = row.unitPrice
      })
    },
    handleAttributeClose() {
      this.$emit('close', null, null, null)
    },
    attrLoading() {
      this.categoryAttrLoading = true
    },
    attrStopLoading() {
      this.categoryAttrLoading = false
    },
    handleAttributeChange() {
      this.$refs.productAttrForm.validate((valid) => {
        if (valid) {
          const result = {
            moldId: this.moldData.id,
            moldName: this.moldData.moldName,
            unit: this.moldData.unit,
            color: this.getAttributeValue('color'),
            material: this.getAttributeValue('material'),
            size: this.getAttributeValue('size'),
            length: this.getAttributeValue('length'),
            quantity: this.productAttr.quantity,
            unitPrice: this.productAttr.unitPrice,
            amount: Number(this.productAttr.quantity) * Number(this.productAttr.unitPrice) + '',
            productName: this.moldData.moldName,
            weight: this.moldData.weight,
            categoryId: this.moldData.categoryId
          }
          this.$emit('close', result)
        }
      })
    },
    getAttributeValue(key) {
      return this.productAttr.categoryAttributeList.filter(e => e.attributeKey === key)[0].value
    },
    saveCategoryAttr(item, index, row) {
      const optional = this.productAttr.categoryAttributeList[index].optional
      if (this.productAttr.newAttr[index].value == null || this.productAttr.newAttr[index].value === '') {
        this.$message.warning('请输入属性值')
        return
      }
      if (optional.indexOf(this.productAttr.newAttr[index].value) !== -1) {
        this.$message.error('已存在相同选项,' + this.productAttr.newAttr[index].value)
        return
      }
      const data = JSON.parse(JSON.stringify(item))
      this.productAttr.categoryAttributeList[index].optional.push(this.productAttr.newAttr[index].value)
      data.optional = this.productAttr.categoryAttributeList[index].optional.join('|')
      this.categoryAttrLoading = true
      updateCategoryAttributeById(data).then(resp => {
        if (resp.success) {
          this.$message.success('添加成功')
          this.productAttr.newAttr[index].value = ''
          row.show = false
        }
      }).finally(() => {
        this.categoryAttrLoading = false
      })
    },
    deleteCategoryAttr(item, index, optional) {
      this.$confirm('是否删除此条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = JSON.parse(JSON.stringify(item))
        const optionalArray = this.productAttr.categoryAttributeList[index].optional
        const indexOf = optionalArray.indexOf(optional)
        if (indexOf !== -1) {
          optionalArray.splice(indexOf, 1)
          this.productAttr.categoryAttributeList[index].optional = optionalArray
          this.categoryAttrLoading = true
          data.optional = optionalArray.join('|')
          updateCategoryAttributeById(data).then(resp => {
            if (resp.success) {
              this.$message.success('删除成功')
            }
          }).finally(() => {
            this.categoryAttrLoading = false
          })
        }
      })
    },
    showInput(row) {
      row.show = true
    },
    disableInput(row) {
      row.show = false
    }
  }
}
</script>

<style scoped>

</style>
